package com.wtb.javatool.service.impl;

import com.wtb.javatool.dao.AttachmentMapper;
import com.wtb.javatool.entity.Attachment;
import com.wtb.javatool.service.AttachmentService;
import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

@Service
public class AttachmentServiceImpl implements AttachmentService {

    private final AttachmentMapper attachmentMapper;

    public AttachmentServiceImpl(AttachmentMapper attachmentMapper) {
        this.attachmentMapper = attachmentMapper;
    }

    /**
     * 根据任务ID，为其添加附件,同时讲文件保存在本地
     *
     * @param taskId    任务ID
     * @param fileItems 文件列表
     */
    @Override
    public void upLoadTaskAttachment(Long taskId, Long creatorId, List<FileItem> fileItems) throws Exception {
        for (FileItem fileItem : fileItems) {
            if (!fileItem.isFormField()) { // 检查是否为文件
                Date date = new Date();
                Attachment attachment = new Attachment();

                attachment.setAttachmentName(fileItem.getName());
                attachment.setSize(fileItem.getSize());
                attachment.setCreateTime(date);
                attachment.setCreatorId(creatorId);
                attachment.setTaskId(taskId);
                attachmentMapper.uploadAttachment(attachment);

                String fileName =  attachment.getAttachmentId() + "_" + fileItem.getName() ;
                String savePath = "E:/uploads/"; // 设置保存路径

                File saveFile = new File(savePath + File.separator + fileName);
                attachment.setAttachmentUrl(saveFile.getPath());
                attachmentMapper.uploadAttachmentUrl(attachment);

                fileItem.write(saveFile); // 将文件写入到本地磁盘
            }
        }
    }

    /**
     * 根据任务ID，返回与任务相关的所有附件
     *
     * @param taskId 任务ID
     * @return 附件列表，具体参数参考Attachment实体
     */
    public List<Attachment> findAttachmentsByTaskId(Long taskId){
        return attachmentMapper.findAttachmentsByTaskId(taskId);
    }

    /**
     * 删除某个附件
     *
     * @param attachmentId 任务ID
     */
    public void deleteAttachmentByAttachmentId(Long attachmentId,String attachmentUrl){
        Path path = Paths.get(attachmentUrl);
        try{
            Files.delete(path);
            attachmentMapper.deleteAttachmentByAttachmentId(attachmentId);
        }
        catch (IOException e) {
            // 处理异常
            System.err.println("删除文件时出错: " + e.getMessage());
        }
    }
}